﻿#include "VerifyCodeWidget.h"
#include <QPainter>
#include <QRandomGenerator>
#include "Debug.h"

/////////////////////////////////////////////////
/// 登录时使用的验证码
/////////////////////////////////////////////////
VerifyCodeWidget::VerifyCodeWidget(QWidget* parent)
    : QWidget(parent)
{
    verify_code = generate_code();
}

/// @brief 重新生成验证码
void VerifyCodeWidget::refresh_verify_code()
{
    verify_code = generate_code();
    update();  // 这个会触发 paintEvent
}

/// @brief 检查验证码是否正确
bool VerifyCodeWidget::check_verify_code(const QString& code)
{
    return QString::compare(code, verify_code, Qt::CaseInsensitive) == 0;  // 忽略大小写
}

/// @brief 绘制这个验证码
void VerifyCodeWidget::paintEvent(QPaintEvent* event)
{
    QPainter painter(this);
    QPen     pen;
    // 使用控件实际大小
    int width  = this->width();
    int height = this->height();
    // 设置字体大小，基于控件高度
    int   fontSize = height * 0.6;
    QFont font("楷体", fontSize, QFont::Bold, true);
    painter.setFont(font);
    // 获取字体度量
    QFontMetrics     metrics(font);
    QRandomGenerator randomGenerator = *QRandomGenerator::global();
    // 画点: 添加随机噪点
    for (int i = 0; i < 100; i++) {
        pen = QPen(QColor(randomGenerator.generate() % 256,
                          randomGenerator.generate() % 256, randomGenerator.generate() % 256));
        painter.setPen(pen);
        painter.drawPoint(randomGenerator.generate() % width,
                          randomGenerator.generate() % height);
    }
    // 画线: 添加随机干扰线
    for (int i = 0; i < 5; i++) {
        pen = QPen(QColor(randomGenerator.generate() % 256,
                          randomGenerator.generate() % 256, randomGenerator.generate() % 256));
        painter.setPen(pen);
        painter.drawLine(randomGenerator.generate() % width,
                         randomGenerator.generate() % height,
                         randomGenerator.generate() % width,
                         randomGenerator.generate() % height);
    }
    // 绘制验证码
    int charWidth = width / (verify_code.size() + 1);
    for (int i = 0; i < verify_code.size(); i++) {
        pen = QPen(QColor(randomGenerator.generate() % 128 + 64,
                          randomGenerator.generate() % 128 + 64,
                          randomGenerator.generate() % 128 + 64));
        painter.setPen(pen);
        // 计算字符位置
        int x = charWidth * i + randomGenerator.generate() % 5;
        // 正确计算垂直居中位置
        int textHeight = metrics.height();
        int y          = (height + textHeight) / 2 - metrics.descent() + (randomGenerator.generate() % 10 - 5);
        painter.drawText(x, y, QString(verify_code[i]));
    }
}

/// @brief 当点击验证码的时候，重新生成验证码
void VerifyCodeWidget::mousePressEvent(QMouseEvent* event)
{
    refresh_verify_code();
}

/// @brief 生成一个4位的只由字母组成的验证码
QString VerifyCodeWidget::generate_code()
{
    QString code;
    for (int i = 1; i <= 4; ++i) {
        code += QChar(QRandomGenerator::global()->bounded(65, 91));  // A-Z
    }
    return code;
}
